package com.labelimage.controller;

import cn.hutool.json.JSONUtil;
import com.labelimage.common.response.WS;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint("/taskWS")
@Slf4j
@Component
public class TaskSocketServer {

    /**
     * concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
     */
    private static ConcurrentHashMap<String, TaskSocketServer> webSocketMap = new ConcurrentHashMap<>();
    /**
     * 与某个客户端的连接会话，需要通过它来给客户端发送数据
     */
    @Getter
    private Session session;

    /**
     * 连接成功
     *
     * @param session
     */
    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        if (webSocketMap.containsKey(session.getId())) {
            webSocketMap.remove(session.getId());
            webSocketMap.put(session.getId(), this);
        } else {
            webSocketMap.put(session.getId(), this);
        }
        log.info("用户连接:" + session.getId());
    }

    /**
     * 连接关闭
     *
     * @param session
     */
    @OnClose
    public void onClose(Session session) {
        if (webSocketMap.containsKey(session.getId())) {
            webSocketMap.remove(session.getId());
        }
        log.info("用户退出:" + session.getId());
    }

    /**
     * 接收到消息
     *
     * @param text
     */
    @OnMessage
    public void onMsg(String text, Session session) throws IOException {
        log.info("接收到用户:",session.getId(),"发送的消息:",text);
    }

    @OnError
    public void onError(Throwable error) {
        log.info("连接错误",error.getMessage());
    }

    public void sendMessage2All(WS<?> ws) throws IOException {
        String message = JSONUtil.toJsonStr(ws);
        for(TaskSocketServer taskSocketServer:webSocketMap.values())
        {
            taskSocketServer.getSession().getBasicRemote().sendText(message);
        }
        log.info("已推送消息给在线的所有用户：",message);
    }

}
